package com.core {

import com.interfaces.IController;
import com.utils.StringUtil;

import laya.utils.Handler;

public class Controller implements IController {

	/** 缓存的所有事件 */
	private var obj:Object = {};

	public function Controller() {
	}

	public function regActionHandler(action:String, handler:Handler, group:String=null):void {
		var groupObj:Object = getGroup(group);
		// 获取此分组下  action 的执行函数存储数组
		if (groupObj[action] == null) groupObj[action] = [];
		groupObj[action].push(handler);
	}

	/**
	 * 分组存储对象
	 * @param group
	 * @return
	 */
	public function getGroup(group:String):Object {
		if (StringUtil.isNullOrEmpty(group)) {
			group = "group";
		}
		var groupObj:Object = obj[group];
		if (groupObj == null) groupObj = {};
		obj[group] = groupObj;
		return groupObj;
	}

	public function regAction(action:String, caller:*, method:Function, group:String=null):void {
		regActionHandler(action, new Handler(caller, method), group);
	}

	public function removeAllAction(...arge):void {
		for each (var o:Object in obj) {
			for (var i:int = 0; i < arge.length; i++) {
				delete o[arge[i]];
			}
		}
	}

	public function removeGroup(group:String):void {
		delete obj[group];
	}

	public function removeGroupActions(group:String, ...arge):void {
		var groupObj:Object = getGroup(group);
		for (var i:int = 0; i < arge.length; i++) {
			delete groupObj[arge[i]];

		}
	}

	public function removeHandler(action:String, method:Function, group:String=null):void {
		if (group == null) {
			for each (var o:Object in obj) {
				removeFunction(o, action, method);
			}
			return;
		}
		var groupObj:Object = getGroup(group);
		removeFunction(groupObj, action, method);
	}

	private function removeFunction(groupObj:Object, action:String, method:Function):void {
		var arr:Array = groupObj[action];
		if (arr) {
			for (var i:int = 0; i < arr.length; i++) {
				var h:Handler = arr[i];
				if (h.method == method) {
					arr.splice(i, 1);
					i--;
				}
			}
			if (arr.length == 0) delete groupObj[action];
		}
	}

	public function sendGroupAction(group:String, action:String, ...arge):void {
		var groupObj:Object = getGroup(group);
		var arr:Array = groupObj[action];
		if (arr) {
			var handler:Handler;
			for (var i:int = 0; i < arr.length; i++) {
				handler = arr[i];
				handler.runWith(arge);
			}
		} else {
			console.warn("group["+group+"], action ["+action+"] not exist! Call failure");
		}
	}

	public function sendAction(action:String, ...arge):void {
		for (var groupName:String in obj) {
			arge.unshift(action);
			arge.unshift(groupName);
			sendGroupAction.apply(this, arge);
		}
	}

}
}
